<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\UserVisitCount;
use Illuminate\Support\Facades\Redis;
class UserVisitInfoCount extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user:visit_info_count';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '用户访问统计入库';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $courseArr = Redis::keys('course_visit_*');
        $articleArr = Redis::keys('article_visit_*');
        logger()->info('用户访问统计');
        foreach($courseArr as $count){
            $info = explode('_',$count);
            $course_num = Redis::get($count);
            if(!isset($info[3])){
                Redis::del($count);
                continue;
            }
            $article_num = Redis::get('article_visit_'.$info[2].'_'.$info[3])?Redis::get('article_visit_'.$info[2].'_'.$info[3]):0;

            $userVisit = UserVisitCount::where('user_id',$info[3])->where('time',$info[2])->first();
            if(!$userVisit){
                $userVisit = new UserVisitCount();
            }

            $userVisit->time = $info[2];
            $userVisit->user_id = $info[3];
            $userVisit->article_visit = $article_num;
            $userVisit->course_visit = $course_num;
            if(!$userVisit->save()){
                $this->info('统计失败');
            }
            Redis::del($count);
            Redis::del('article_visit_'.$info[2].'_'.$info[3]);
        }
        $this->info('用户统计完成');
    }
}